package Games.Gobang.Bluetooth;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public final class SerializationHelper {

	private SerializationHelper() {
	}

	public static Object clone(Serializable object)
			throws SerializationException {
		return deserialize(serialize(object));
	}

	public static void serialize(Serializable obj, OutputStream outputStream)
			throws SerializationException {
		if (outputStream == null) {
			throw new IllegalArgumentException(
					"The OutputStream must not be null");
		}

		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(outputStream);
			out.writeObject(obj);
		} catch (IOException ex) {
			throw new SerializationException("could not serialize", ex);
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException ignored) {
			}
		}
	}

	public static byte[] serialize(Serializable obj)
			throws SerializationException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
		serialize(obj, baos);
		return baos.toByteArray();
	}

	public static Object deserialize(InputStream inputStream)
			throws SerializationException {
		if (inputStream == null) {
			throw new IllegalArgumentException(
					"The InputStream must not be null");
		}

		ObjectInputStream in = null;
		try {
			// stream closed in the finally
			in = new ObjectInputStream(inputStream);
			return in.readObject();

		} catch (ClassNotFoundException ex) {
			throw new SerializationException("could not deserialize", ex);
		} catch (IOException ex) {
			throw new SerializationException("could not deserialize", ex);
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException ex) {
			}
		}
	}

	public static Object deserialize(byte[] objectData)
			throws SerializationException {
		if (objectData == null) {
			throw new IllegalArgumentException("The byte[] must not be null");
		}
		ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
		return deserialize(bais);
	}
}